package thread.blockqueue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author yuisama
 * @date 2022/06/25 12:02
 **/
public class Test {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(3);
        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    // 当阻塞队列为空，take方法就会阻塞
                    int val = blockingQueue.take();
                    System.out.println("消费元素 : " + val);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "消费者");
        Random random = new Random();
        Thread producer = new Thread(() -> {
            while (true) {
                try {
                    int val = random.nextInt(100);
                    // 当队列已满，put方法就会阻塞
                    blockingQueue.put(val);
                    System.out.println("生产元素 : " + val);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "生产者");
        customer.start();
        producer.start();
    }
}